package push.tools.service.service.egova;

import com.alibaba.fastjson2.JSON;

import com.alibaba.fastjson2.JSONObject;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import push.tools.service.constant.ApiUrl;

import java.util.HashMap;

@Service
public class AuthenticationService {
    private static final Logger logger = LoggerFactory.getLogger(AuthenticationService.class);

    @Autowired
    public OkHttpClient okHttpClient;

    public String getToken() {
        //请求参数
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("client_id", "10001");
        paramsMap.put("client_secret", "dd91a0180a");
        paramsMap.put("grant_type", "client_credentials");
        String paramsString = JSON.toJSONString(paramsMap);
        //构建请求体
        RequestBody body = RequestBody.create(paramsString, MediaType.get("application/json; charset=UTF-8"));
        Request request = new Request.Builder()//
                .url(ApiUrl.getToken)//请求连接
                .post(body)//请求体
                .build();//构建
        //同步请求
        try (Response response = okHttpClient.newCall(request).execute()) {
            String respString = response.body().string();
            JSONObject jsonObject = (JSONObject) JSON.parse(respString);
            String accessToken = jsonObject.getString("access_token");
            if (accessToken == null || accessToken.isEmpty()) {
                throw new RuntimeException("获取英德城管token失败:token为空");
            }
            logger.warn("获取英德城管token成功: {}", accessToken);
            return accessToken;
        } catch (Exception e) {
            throw new RuntimeException("获取英德城管token失败:" + e.getMessage());
        }
    }

}
